
package utils.dataaccess;

import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import managedbeans.RegistrationBean;


public class IOUtil {
    
    static{
        File avatarFolder = new File(getProjectRoot()+"/images/avatars");
        if(!avatarFolder.exists())
            avatarFolder.mkdirs();
        File storageFolder = new File(getProjectRoot()+"/storage");
        if(!storageFolder.exists())
            storageFolder.mkdirs();
        File configFolder = new File(getProjectRoot()+"/config");
        if(!configFolder.exists())
            configFolder.mkdirs();
    }
    
    
    public static void updateAvatar(byte[] avatarBytes, String username){
            try{
                
                String avatarFilename = getProjectRoot()+"images/avatars/"+username+".png";
                System.out.println(avatarFilename);               
                File avatarFile = new File(avatarFilename);
                FileOutputStream fos = new FileOutputStream(avatarFile);
                fos.write(avatarBytes);
                fos.close();
                    
            }catch(IOException ex){
                System.err.println(ex.toString());
            }
    }
    
    private static void setDefaultAvatar(String username){
        String strangerAvatarFilename = getProjectRoot()+"/images/stranger.png";
        File strangerAvatarFile = new File(strangerAvatarFilename);
        String avatarFilename = getProjectRoot()+"/images/avatars/"+username+".png";
        File avatarFile = new File(avatarFilename);
        copyFile(strangerAvatarFile, avatarFile);
    }
    
    public static  void saveAvatar(byte[] avatarBytes, String username){  
        if(avatarBytes != null){
            updateAvatar(avatarBytes, username);
        } else {
            setDefaultAvatar(username);
        }
    }
    
    public static String getProjectRoot(){
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        return externalContext.getRealPath("/");
    }
    
    private static void copyFile(File source, File destination){
        InputStream in = null;
        OutputStream out = null;
        try {
            in = new FileInputStream(source);
            out = new FileOutputStream(destination);
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            in.close();
            out.close();
        } catch (IOException ex) {
            Logger.getLogger(RegistrationBean.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                in.close();
                out.close();
            } catch (IOException ex) {
                Logger.getLogger(RegistrationBean.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    
    public static boolean deleteDirectory(File path) {
    if( path.exists() ) {
      File[] files = path.listFiles();
      for(int i=0; i<files.length; i++) {
         if(files[i].isDirectory()) {
           deleteDirectory(files[i]);
         }
         else {
           files[i].delete();
         }
      }
    }
    return( path.delete() );
   }

    public static void saveFile(byte[] fileBytes, String fileName){
           if(fileBytes!=null && fileName != null){
                try{           
                        File file = new File(getProjectRoot()+"/storage/"+fileName);
                        FileOutputStream fos = new FileOutputStream(file);
                        fos.write(fileBytes);
                        fos.close();
                }catch(IOException ex){
                        System.err.println(ex.toString());
                }
           }
    }

    public static void deleteFile(String fileName) {
        File file = new File(getProjectRoot()+"/storage/"+fileName);
        file.delete();
    }
    
    /**
     * Resolves a class name for database utility's inversion of control
     */
    public static String loadClassName() throws IOException {
        String classSimpleName = "HibernateUtil";
        File file = new File(getProjectRoot()+"/config/dbselector.ini");
        if( file.exists() ) {
            BufferedReader reader = new BufferedReader(new FileReader(file));
            classSimpleName = reader.readLine();
            reader.close();
        } else {
            file.createNewFile();
            saveClassName("HibernateUtil");
        }
        return classSimpleName;
    }
    
    public static void saveClassName(String className) throws IOException {
        
        File file = new File(getProjectRoot()+"/config/dbselector.ini");
        if( !file.exists() ) {
            file.createNewFile();
        }
        
        write(file, className);
        
    }
    
    public static void write(File filename, String content){
        BufferedWriter writer = null;
        try {
            writer = new BufferedWriter(new FileWriter(filename));
            writer.write(content);
            writer.close();
        } catch (IOException ex) {
            Logger.getLogger(IOUtil.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                writer.close();
            } catch (IOException ex) {
                Logger.getLogger(IOUtil.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    
    public static String read(File filename){
        String result = "";

        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(filename));
            String buffer;
            while((buffer = reader.readLine()) != null){
                result += (buffer+"\n");
            }
            reader.close();
        } catch (IOException ex) {
            Logger.getLogger(IOUtil.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                reader.close();
            } catch (IOException ex) {
                Logger.getLogger(IOUtil.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return result;
    }
    
}
